package com.plian.system.controller.pm.annualdonation;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.*;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.dto.pm.annualdonationrecordmain.AnnualDonationRecordMainDTO;
import com.plian.system.entity.pm.annualdonationrecord.AnnualDonationRecord;
import com.plian.system.entity.pm.annualdonationrecordmain.AnnualDonationRecordMain;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.pm.annualdonationrecordmain.IAnnualDonationRecordMainService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pm.annualdonationrecordmain.AnnualDonationRecordMainVO;
import com.plian.system.vo.pm.annualdonationrecordmain.AnnualDonationRecordStatisticalDetailVO;
import com.plian.system.vo.pm.annualdonationrecordmain.AnnualDonationRecordStatisticalVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.wrapper.pm.annualdonationrecordmain.AnnualDonationRecordMainWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
 * 企业年度捐赠计划备案 控制器
 *
 * @author gangan
 * @since 2019-10-24
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/api/annualdonationrecordmain")
@Api(value = "企业年度捐赠计划备案", tags = "企业年度捐赠计划备案")
public class AnnualDonationRecordMainController extends BaseController {

    private IAnnualDonationRecordMainService annualDonationRecordMainService;

    private FormWorkflowService formWorkflowService;

    private AnnualDonationRecordMainWrapper annualDonationRecordMainWrapper;


    /**
     * 详情,计划执行参照时显示没有被选过的参照
     */
    @PostMapping("/preDetail")
    public R<AnnualDonationRecordMainVO> preDetail(@RequestBody AnnualDonationRecordMain annualDonationRecordMain) {
        AnnualDonationRecordMainVO detail = annualDonationRecordMainWrapper
                .entityToVO(annualDonationRecordMainService.getOne(Condition.getQueryWrapper(annualDonationRecordMain)));
        return annualDonationRecordMainService.getPreDetailObj(detail);
    }

    /**
     * 详情,计划执行根据年度获取所有子表
     */
    @PostMapping("/refByYear")
    public R<AnnualDonationRecordMainVO> refByYear(@RequestBody AnnualDonationRecordMain annualDonationRecordMain) {
        return annualDonationRecordMainService.refByYear(annualDonationRecordMain.getYear());
    }

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<AnnualDonationRecordMainVO> detail(@RequestBody AnnualDonationRecordMain annualDonationRecordMain) {
        AnnualDonationRecordMainVO detail = annualDonationRecordMainWrapper
                .entityToVO(annualDonationRecordMainService.getOne(Condition.getQueryWrapper(annualDonationRecordMain)));
        return annualDonationRecordMainService.getDetailObj(detail);
    }

    /**
     * 分页 企业年度捐赠计划备案
     */
    @PostMapping("/list")
    public ListResult<AnnualDonationRecordMainVO> list(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<AnnualDonationRecordMain> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new AnnualDonationRecordMain()), entityList
        );
        TokenSearch<AnnualDonationRecordMain> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);

        IPage<AnnualDonationRecordMain> pages = annualDonationRecordMainService.page(Condition.getPage(query), queryWrapper);
        List<AnnualDonationRecordMainVO> annualDonationRecordMainVOS = annualDonationRecordMainWrapper.entityToVO(pages.getRecords());
        ListResult<AnnualDonationRecordMainVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(annualDonationRecordMainVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 分页 企业年度捐赠计划备案参照页面
     */
    @PostMapping("/preList")
    public ListResult<AnnualDonationRecordMainVO> preList(@RequestBody Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        QueryWrapper<AnnualDonationRecordMain> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new AnnualDonationRecordMain()), entityList
        );
        queryWrapper.eq("report_company_id", TokenUtil.getTokenOrgId());
        IPage<AnnualDonationRecordMain> pages = annualDonationRecordMainService.preList(Condition.getPage(query), queryWrapper);
        List<AnnualDonationRecordMainVO> annualDonationRecordMainVOS = annualDonationRecordMainWrapper.entityToVO(pages.getRecords());
        ListResult<AnnualDonationRecordMainVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(annualDonationRecordMainVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    /**
     * 新增或修改 企业年度捐赠计划备案
     */
    @PostMapping("/submit")
    @LogOperation("企业年度捐赠计划备案-提交")
    @Resubmit(delaySeconds = 0)
    public R submit(@Valid @RequestBody AnnualDonationRecordMain annualDonationRecordMain) {
        String checkResult = annualDonationRecordMainService.checkIsExisted(annualDonationRecordMain.getId(), annualDonationRecordMain.getCode(), annualDonationRecordMain.getFilingCode());
        if (!StringUtil.isEmpty(checkResult)) {
            return new R(CustomCode.builder().message(checkResult).code(1999).success(false).build());
        }
        boolean result = annualDonationRecordMainService.submit(annualDonationRecordMain);
        HashMap<String, Object> processVariable = new HashMap<>();
        Double amount = 0d;
        if (annualDonationRecordMain != null && annualDonationRecordMain.getAnnualDonationRecords() != null && annualDonationRecordMain.getAnnualDonationRecords().size() > 0) {
            List<AnnualDonationRecord> records = annualDonationRecordMain.getAnnualDonationRecords();
            for (AnnualDonationRecord record : records) {
                if (record != null && record.getDonationAmount() != null) {
                    amount += record.getDonationAmount().doubleValue();
                }
            }

        }
        processVariable.put("juanzengjine", amount * 10000);
        if (annualDonationRecordMainService.checkJzjh(annualDonationRecordMain.getId())) {//为了不改流程图就判断为true就复制50000以上
            processVariable.put("juanzengjine", 500000);
        } else {
            processVariable.put("juanzengjine", 0);
        }
        formWorkflowService.startProcessAndSimulate(String.valueOf(annualDonationRecordMain.getId()), annualDonationRecordMain.getFormType(), processVariable);
        return result ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 删除 企业年度捐赠计划备案
     */
    @PostMapping("/remove")
    @LogOperation("企业年度捐赠计划备案-删除")
    public R remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        return annualDonationRecordMainService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
    }

    /**
     * 打印
     */
    @GetMapping("/buildpdfold/{id}")
//	@PassToken
    public ResponseEntity<FileSystemResource> buildPdf(@PathVariable Long id) {
        return FileTools.exportPdf(annualDonationRecordMainService.createReceptFile(id));
    }

    /**
     * 打印
     */
    @GetMapping("/buildpdf/{id}")
//	@PassToken
    public void buildPdfNew(@PathVariable Long id, HttpServletResponse response) {
        File receptFile = annualDonationRecordMainService.createReceptFile(id);
        String fileName = "";
        try {
            fileName = receptFile.getName().split("&&")[0] + ".pdf";
            fileName = new String(fileName.getBytes("GB2312"), "ISO_8859_1");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            InputStream inputStream = new FileInputStream(receptFile);
            // 激活下载操作
            OutputStream os = response.getOutputStream();
            // 循环写入输出流
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            // 这里主要关闭。
            os.close();
            inputStream.close();
        } catch (UnsupportedEncodingException e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        } catch (FileNotFoundException e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        } catch (IOException e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
    }

    /**
     * 下载doc
     */
    @GetMapping("/buildword/{id}")
//	@PassToken
    public void buildword(@PathVariable Long id, HttpServletResponse response) {
        annualDonationRecordMainService.buildword(id, response);
    }


    @PostMapping("/annualDonationRecordStatistical")
    @ApiOperation(value = "以备案号排序的年度捐赠计划备案统计报表", notes = "传入year yyyy、orgIds 单位id")
    public R<List<AnnualDonationRecordStatisticalVO>> annualDonationRecordStatistical(@RequestBody AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        R<List<AnnualDonationRecordStatisticalVO>> r = new R<>(CommonCode.SUCCESS);
        r.setPageData(annualDonationRecordMainService.annualDonationRecordStatistical(annualDonationRecordMainDTO));
        return r;
    }

    @PostMapping("/annualDonationRecordStatisticalDetail")
    @ApiOperation(value = "以备案号排序的年度捐赠计划备案统计报表 明细", notes = "传入id 单据id")
    public R<List<AnnualDonationRecordStatisticalDetailVO>> annualDonationRecordStatisticalDetail(@RequestBody AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        R<List<AnnualDonationRecordStatisticalDetailVO>> r = new R<>(CommonCode.SUCCESS);
        r.setPageData(annualDonationRecordMainService.annualDonationRecordStatisticalDetail(annualDonationRecordMainDTO));
        return r;
    }

    @PostMapping("/annualDonationYearStatistical")
    @ApiOperation(value = "以集团为单位的年度捐赠计划/执行统计报表", notes = "传入year yyyy、orgIds 单位id、statisticalType 统计类型  1计划 2执行")
    public R<ReportReturnVO> annualDonationYearStatistical(@RequestBody AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        if (annualDonationRecordMainDTO.getStatisticalType() == null || annualDonationRecordMainDTO.getStatisticalType() == 0) {
            return new R(CustomCode.builder().message("统计类型为空").code(1999).success(false).build());
        }
        if (StringUtil.isBlank(annualDonationRecordMainDTO.getYear())) {
            annualDonationRecordMainDTO.setYear(DateUtil.format(DateUtil.now(), DateUtil.PATTERN_YEAR));
        }
        R<ReportReturnVO> r = new R<>(CommonCode.SUCCESS);
        r.setPageData(annualDonationRecordMainService.annualDonationYearStatistical(annualDonationRecordMainDTO));
        return r;
    }

    @PostMapping("/annualDonationYearStatisticalDetail")
    @ApiOperation(value = "以集团为单位的年度捐赠计划/执行统计 明细", notes = "传入year yyyy/ lastYear yyyy、reportCompanyId 填报单位id、detailColumnName 统计明细 字段名")
    public R<ReportReturnVO> annualDonationYearStatisticalDetail(@RequestBody AnnualDonationRecordMainDTO annualDonationRecordMainDTO) {
        if (StringUtil.isBlank(annualDonationRecordMainDTO.getDetailColumnName())) {
            return new R(CustomCode.builder().message("统计明细字段名为空").code(1999).success(false).build());
        }

        R<ReportReturnVO> r = new R<>(CommonCode.SUCCESS);
        r.setPageData(annualDonationRecordMainService.annualDonationYearStatisticalDetail(annualDonationRecordMainDTO));
        return r;
    }
}
